import { Elysia, t } from 'elysia';
import { 
  getSettings, 
  getSetting, 
  updateSetting, 
  updateSettings, 
  deleteSetting,
  createBackup,
  getBackups,
  downloadBackup,
  deleteBackup,
  restoreBackup,
  getProductTags,
  updateProductTags,
  getProductCategories,
  updateProductCategories,
  getCaseTags,
  updateCaseTags,
  getCaseCategories,
  updateCaseCategories
} from '../controllers/settingsController';

import { guestAccessMiddleware } from '../middleware/auth';
import { eq, inArray } from 'drizzle-orm';
import { db } from '../db';
import { settings } from '../db/schema';

export const settingsRoutes = new Elysia({ prefix: '/settings' })
  // 公共设置接口（无需认证）
  .get('/public', async ({ set }) => {
    try {
      const publicSettings = await db.select()
        .from(settings)
        .where(inArray(settings.key, [
          'contact_modal'
        ]));

      // 转换为对象格式
      const settingsObj = publicSettings.reduce((acc, setting) => {
        try {
          // 尝试解析JSON字符串
          acc[setting.key] = JSON.parse(setting.value);
        } catch {
          // 如果不是JSON，直接使用字符串值
          acc[setting.key] = setting.value;
        }
        return acc;
      }, {} as Record<string, any>);

      return {
        success: true,
        data: settingsObj
      };
    } catch (error) {
      console.error('Get public settings error:', error);
      set.status = 500;
      return {
        success: false,
        message: '获取公共设置失败'
      };
    }
  })


  
  // 公开的分类和标签接口（无需认证）
  .get('/product-tags', getProductTags, {
    detail: {
      tags: ['Settings', 'Tags'],
      summary: '获取产品标签',
      description: '获取所有产品标签列表'
    }
  })
  .get('/product-categories', getProductCategories, {
    detail: {
      tags: ['Settings', 'Categories'],
      summary: '获取产品分类',
      description: '获取所有产品分类列表'
    }
  })
  .get('/case-tags', getCaseTags, {
    detail: {
      tags: ['Settings', 'Tags'],
      summary: '获取案例标签',
      description: '获取所有案例标签列表'
    }
  })
  .get('/case-categories', getCaseCategories, {
    detail: {
      tags: ['Settings', 'Categories'],
      summary: '获取案例分类',
      description: '获取所有案例分类列表'
    }
  })
  
  // 需要登录权限的路由（游客可查看，管理员可编辑）
  .use(guestAccessMiddleware())
  
  // 设置管理
  .get('/', getSettings, {
    detail: {
      tags: ['Settings'],
      summary: '获取所有设置',
      description: '获取系统所有设置项'
    }
  })
  .put('/', updateSettings, {
    detail: {
      tags: ['Settings'],
      summary: '批量更新设置',
      description: '批量更新多个设置项'
    },
    body: t.Object({}, { description: '设置数据对象' })
  })
  .get('/:key', getSetting, {
    detail: {
      tags: ['Settings'],
      summary: '获取单个设置',
      description: '根据键名获取单个设置项'
    },
    params: t.Object({
      key: t.String({ description: '设置项键名' })
    })
  })
  .put('/:key', updateSetting, {
    detail: {
      tags: ['Settings'],
      summary: '更新单个设置',
      description: '更新指定键名的设置项'
    },
    params: t.Object({
      key: t.String({ description: '设置项键名' })
    }),
    body: t.Object({
      value: t.Any({ description: '设置值' }),
      description: t.Optional(t.String({ description: '设置描述' }))
    })
  })
  .delete('/:key', deleteSetting, {
    detail: {
      tags: ['Settings'],
      summary: '删除设置',
      description: '删除指定键名的设置项'
    },
    params: t.Object({
      key: t.String({ description: '设置项键名' })
    })
  })
  
  // 数据备份管理
  .post('/backup', createBackup, {
    detail: {
      tags: ['Settings', 'Backup'],
      summary: '创建数据备份',
      description: '创建系统数据备份文件'
    }
  })
  .get('/backups', getBackups, {
    detail: {
      tags: ['Settings', 'Backup'],
      summary: '获取备份列表',
      description: '获取所有可用的数据备份文件列表'
    }
  })
  .get('/backup/:filename', downloadBackup, {
    detail: {
      tags: ['Settings', 'Backup'],
      summary: '下载备份文件',
      description: '下载指定的备份文件'
    },
    params: t.Object({
      filename: t.String({ description: '备份文件名' })
    })
  })
  .delete('/backup/:filename', deleteBackup, {
    detail: {
      tags: ['Settings', 'Backup'],
      summary: '删除备份文件',
      description: '删除指定的备份文件'
    },
    params: t.Object({
      filename: t.String({ description: '备份文件名' })
    })
  })
  .post('/restore/:filename', restoreBackup, {
    detail: {
      tags: ['Settings', 'Backup'],
      summary: '恢复数据备份',
      description: '从指定备份文件恢复数据'
    },
    params: t.Object({
      filename: t.String({ description: '备份文件名' })
    })
  })
  
  // 标签和分类管理（更新操作需要认证）
  .put('/product-tags', updateProductTags, {
    detail: {
      tags: ['Settings', 'Tags'],
      summary: '更新产品标签',
      description: '更新产品标签列表'
    },
    body: t.Object({
      tags: t.Array(t.String(), { description: '标签数组' })
    })
  })
  .put('/product-categories', updateProductCategories, {
    detail: {
      tags: ['Settings', 'Categories'],
      summary: '更新产品分类',
      description: '更新产品分类列表'
    },
    body: t.Object({
      categories: t.Array(t.String(), { description: '分类数组' })
    })
  })
  .put('/case-tags', updateCaseTags, {
    detail: {
      tags: ['Settings', 'Tags'],
      summary: '更新案例标签',
      description: '更新案例标签列表'
    },
    body: t.Object({
      tags: t.Array(t.String(), { description: '标签数组' })
    })
  })
  .put('/case-categories', updateCaseCategories, {
    detail: {
      tags: ['Settings', 'Categories'],
      summary: '更新案例分类',
      description: '更新案例分类列表'
    },
    body: t.Object({
      categories: t.Array(t.String(), { description: '分类数组' })
    })
  });